package com.yy.micro.magic.core.filter;

import com.yy.micro.magic.core.annotation.Filter;
import com.yy.micro.magic.core.config.Content;
import com.yy.micro.magic.core.context.ComponentManager;
import com.yy.micro.magic.core.model.ResultCollector;
import com.yy.micro.magic.core.model.RuntimeMetadata;
import com.yy.micro.magic.core.strategy.RuleStrategy;
import com.yy.micro.magic.exception.MapException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
 /**
   * @author YY
   * @version 1.0.0
   * @update 2021/9/22 9:11 下午
   * @description: 一个特殊的{@link MagicFilter},order为99，默认应该是FilterChain的最后一个链。
  * 在构建基于planCode的FilterChain时，会自动追加到链的末尾。该Filter根据变换规则中指定的"strategy"从资源管理器中找到对应的{@link RuleStrategy#process}并执行.
 */
@Filter(Content.STRATEGY_MAP_FILTER)
@Order(99)
public class StrategyFilter implements MagicFilter {

    @Autowired
    private ComponentManager manager;

    @Override
    public void doFilter(final RuntimeMetadata metadata, final ResultCollector collector, final FilterChain filterChain) {
        if (metadata.isIncludeRuntime()){
            RuleStrategy strategy = manager.getRuleStrategy(metadata.getStrategy());
            if (null != strategy && strategy.support(metadata)){
                strategy.process(metadata,collector);
            }else{
                throw new MapException("Can not find rule strategy " + metadata.getStrategy());
            }
        }
    }
}
